#include"mystdio.h"


myFILE* my_fopen(const char* path,const char* mode)
{
  int flag=0;
  int iscreate=0;
  if(strcmp(mode,"r")==0)
  {
    flag=(O_RDONLY);
  }
  else if(strcmp(mode,"w")==0)
  {
    flag=(O_WRONLY | O_CREAT | O_TRUNC);
    iscreate=1;
  }
  else if(strcmp(mode,"a")==0)
  {
    flag=(O_WRONLY | O_CREAT | O_APPEND);
    iscreate=1;
  }
  else 
  {}

  int fd=0;
  if(iscreate)
  {
    fd=open(path,flag,0666);
  }
  else 
  {
    fd=open(path,flag);
  }
  if(fd<0) return NULL;

  myFILE* fp=(myFILE*)malloc(sizeof(myFILE));
  fp->fileno=fd;
  fp->flags=FLUSH_LINE;
  fp->cap=LINE_SIZE;
  fp->pos=0;

  return fp;
}

void my_fflush(myFILE* fp)
{
  write(fp->fileno,fp->cache,fp->pos);
  fp->pos=0;
}


int my_fwrite(myFILE* fp,const char* buf,int len)
{
  memcpy(fp->cache+fp->pos,buf,len);
  fp->pos+=len;

  if((fp->flags&FLUSH_LINE) && (fp->cache[fp->pos-1]=='\n'))
  {
    my_fflush(fp);
  }
  return len;
}



void my_fclose(myFILE* fp)
{
  my_fflush(fp);
  close(fp->fileno);
  free(fp);
}

